import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.util.Scanner;

import org.bouncycastle.crypto.*;
import org.bouncycastle.crypto.engines.RC4Engine;
import org.bouncycastle.crypto.params.KeyParameter;

public class Krypt1 {
	
	public static byte[] Procces(byte[] text,byte[] keyBytes,boolean forencryption)
	{
        StreamCipher rc4 = new RC4Engine();
        KeyParameter keyParam = new KeyParameter(keyBytes);
        rc4.init(forencryption, keyParam); 						//forencryption boolean - szyfrowanie / deszyfrowanie 
        byte[] result = new byte[text.length];
        rc4.processBytes(text, 0, text.length, result, 0);
        return result;
	}
	
	public static void main(String[] args) throws Exception
    {	
		try{
			//loading KeyStore password	
			System.out.print("KeyStore Password: ");
			Scanner input = new Scanner(System.in);
			String KeyStorePass = input.nextLine();
			
			KeyStore key = KeyStore.getInstance("BKS");		
			char[] password = KeyStorePass.toCharArray();
			key.load(new FileInputStream("/home/rafal/key.bks"),password);			

			// loading Alias & Key password			
			System.out.print("Alias: ");
			String Alias = input.nextLine();
			
			System.out.print("Key Password: ");
			String KeyPass = input.nextLine();
			input.close();
			
			KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KeyPass.toCharArray());
			KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) key.getEntry(Alias, protParam);
	
			byte[] keyBytes = pkEntry.getPrivateKey().getEncoded();     	
			
			// loading path to file 
	        Path path = Paths.get(args[0]);
	        byte[] m = Files.readAllBytes(path);
	        
	        // out file with encrypt text
	        FileOutputStream out = new FileOutputStream(new File("file1.txt"));
	        
	    	byte[] encrypt = Procces( m ,keyBytes,true);	// encrypt
	    	
	    	String a = "";
	    	for(byte b : encrypt){
	    		a = a + Integer.toHexString(b & 0xFF);
	    	}
	    	
	    	out.write(a.getBytes());
	    	out.close();
	    	
	    	// out file with decrypt text
	        out = new FileOutputStream(new File("file2.txt"));
	        
	        byte[] decrypt = Procces(encrypt,keyBytes,false);	// decrypt
	        
	        out.write(decrypt);       
	        out.close();
	        
	        System.out.println("Ok");
		}
		catch(Exception e) { System.out.println(e.getMessage()); } 
	}
	
}